﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ESRI.ArcGIS.Display;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.DataSourcesFile;
using ESRI.ArcGIS.Geoprocessor;
using ESRI.ArcGIS.DataManagementTools;
using ESRI.ArcGIS.SpatialAnalyst;
using ESRI.ArcGIS.DataSourcesRaster;
using ESRI.ArcGIS.GeoAnalyst;
using System.Data;

namespace WindowsFormsApp1
{
    class MyTools
    {
        const bool TrueFlag = true;
        const bool FlaseFlag = false;
        public static string OpenFile(string title, string filter)
        {
            System.Windows.Forms.OpenFileDialog openFileDialog;
            openFileDialog = new OpenFileDialog();
            openFileDialog.Title = title;
            openFileDialog.Filter = filter;
            openFileDialog.ShowDialog();
            return openFileDialog.FileName;
        }
        public static string OpenBrowser(string title)
        {
            System.Windows.Forms.FolderBrowserDialog folderBrowserDialog;
            folderBrowserDialog = new FolderBrowserDialog();
            folderBrowserDialog.Description = title;
            folderBrowserDialog.ShowDialog();
            return folderBrowserDialog.SelectedPath;
        }
        public static IAlgorithmicColorRamp MakeColorRamp(IColor SColor,IColor EColor,int count)
        {
            bool Flag = true;
            IAlgorithmicColorRamp pAlgorithmicCR = new AlgorithmicColorRampClass();
            pAlgorithmicCR.Algorithm = esriColorRampAlgorithm.esriHSVAlgorithm;
            pAlgorithmicCR.FromColor = SColor;
            pAlgorithmicCR.ToColor = EColor;
            pAlgorithmicCR.Size = count;
            pAlgorithmicCR.CreateRamp(out Flag);
            return pAlgorithmicCR;
        }
        public static IRgbColor ErsiColor(int R,int G,int B)
        {
            IRgbColor rgbColor = new RgbColorClass();
            rgbColor.Red = R;
            rgbColor.Blue = G;
            rgbColor.Green = B;
            return rgbColor;
        }
        public static IFeatureClass JoinFieldAPI(ILayer inLayer,ITable inTable,string LayerField,string TableField)
        {
            IFeatureLayer featureLayer = inLayer as IFeatureLayer;
            IFeatureClass featureClass = featureLayer.FeatureClass;

            IMemoryRelationshipClassFactory pMemRelClassFactory = new MemoryRelationshipClassFactoryClass();
            IRelationshipClass pRelaClass = pMemRelClassFactory.Open("JoinName", inLayer as IObjectClass, LayerField,inTable as IObjectClass, TableField, "Forward", "Backward", esriRelCardinality.esriRelCardinalityOneToOne);
            IDisplayRelationshipClass pDisplayRelationshipC = featureLayer as IDisplayRelationshipClass;
            pDisplayRelationshipC.DisplayRelationshipClass(pRelaClass, esriJoinType.esriLeftInnerJoin);
            IDisplayTable displaytable = pDisplayRelationshipC as IDisplayTable;
            IFeatureClass outf = displaytable.DisplayTable as IFeatureClass;
            return outf;
        }
        public static ITable JoinFieldAPI(ITable basic,ITable Out,string BasicField,string OutField)
        {
            Geoprocessor gp = new Geoprocessor();
            gp.OverwriteOutput = true;
            JoinField jf = new JoinField();
            jf.in_data = basic;//基表
            jf.in_field = BasicField;//基表连接字段
            jf.join_table = Out;//外表
            jf.join_field = OutField; //外表连接字段               
            gp.Execute(jf, null);
            return basic;
        }
        public static DataTable ToDataTable(ITable mTable)
        {
            try
            {
                DataTable pTable = new DataTable();
                for (int i = 0; i < mTable.Fields.FieldCount; i++)
                {
                    pTable.Columns.Add(mTable.Fields.get_Field(i).Name);
                }

                ICursor pCursor = mTable.Search(null, false);
                IRow pRrow = pCursor.NextRow();
                while (pRrow != null)
                {
                    DataRow pRow = pTable.NewRow();
                    string[] StrRow = new string[pRrow.Fields.FieldCount];
                    for (int i = 0; i < pRrow.Fields.FieldCount; i++)
                    {
                        StrRow[i] = pRrow.get_Value(i).ToString();
                    }
                    pRow.ItemArray = StrRow;
                    pTable.Rows.Add(pRow);
                    pRrow = pCursor.NextRow();
                }
                return pTable;
            }
            catch (Exception ex)
            {
                return null;
            }
        }
        public static IFeatureLayer AddShpFile(string FileName)
        {
            System.Diagnostics.Debug.WriteLine(FileName);
            if (FileName != "")
            {
                string BrowserPath = System.IO.Path.GetDirectoryName(FileName);
                string ShpFileName = System.IO.Path.GetFileNameWithoutExtension(FileName);
                IWorkspaceFactory workspaceFactory = new ShapefileWorkspaceFactory();
                IFeatureWorkspace featureWorkspace = workspaceFactory.OpenFromFile(BrowserPath, 0) as IFeatureWorkspace;
                IFeatureClass featureClass = featureWorkspace.OpenFeatureClass(ShpFileName);
                IFeatureLayer featureLayer = new FeatureLayer();
                featureLayer.FeatureClass = featureClass;
                IDataset dataset = featureClass as IDataset;
                featureLayer.Name = dataset.Name;

                return featureLayer;
            }
            return null;
        }

        public static ITable AddDbfTable(string FileName)
        {
            System.Diagnostics.Debug.WriteLine(FileName);
            if (FileName != "")
            {
                string BrowserPath = System.IO.Path.GetDirectoryName(FileName);
                string ShpFileName = System.IO.Path.GetFileNameWithoutExtension(FileName);
                IWorkspaceFactory workspaceFactory = new ShapefileWorkspaceFactory();
                IFeatureWorkspace featureWorkspace = workspaceFactory.OpenFromFile(BrowserPath, 0) as IFeatureWorkspace;

                ITable table = featureWorkspace.OpenTable(ShpFileName);
                return table;
            }
            return null;
        }
        public static void MakeCombo(ref ComboBox box,ITable table)
        {
            box.Items.Clear();
            for (int i = 0; i < table.Fields.FieldCount; i++)
            {
                box.Items.Insert(i, table.Fields.get_Field(i).Name);
            }
        }
        public static IRasterLayer CalMinPath(IRasterLayer sourceRasterlayer,IRasterLayer endRasterLayer,IRasterLayer costRasterlayer,string outputFileName)
        {
            if (System.IO.File.Exists(outputFileName))
            {
                System.IO.File.Delete(outputFileName);
            }

            IGeoDataset sourceRaster = sourceRasterlayer.Raster as IGeoDataset;

            IGeoDataset costRaster = costRasterlayer.Raster as IGeoDataset;

            IDistanceOp2 distanceOp = new RasterDistanceOpClass();
            IRasterAnalysisEnvironment rasAnaEnv = distanceOp as IRasterAnalysisEnvironment;

            //设置生成图层的工作空间
            IWorkspaceFactory wsf = new RasterWorkspaceFactoryClass();
            string outputPath = System.IO.Path.GetDirectoryName(outputFileName);
            string fileName = System.IO.Path.GetFileName(outputFileName);
            IWorkspace ws = wsf.OpenFromFile(outputPath, 0);
            rasAnaEnv.OutWorkspace = ws;

            //设置生成图层的范围
            object extent = (object)costRaster.Extent;
            object missing = System.Reflection.Missing.Value;
            rasAnaEnv.SetExtent(esriRasterEnvSettingEnum.esriRasterEnvValue, ref extent, ref missing);

            //设置生成图层的栅格大小
            rasAnaEnv.SetCellSize(esriRasterEnvSettingEnum.esriRasterEnvMinOf);
            //进行成本距离的计算 
            object maxDistance = System.Reflection.Missing.Value;
            object valueRaster = System.Reflection.Missing.Value;


            IGeoDataset DisDataset = distanceOp.CostDistance(sourceRaster, costRaster, ref maxDistance, ref valueRaster);
            //生成的IRaster是保存在内存中的数据，要保存在硬盘文件中还应使用ISaveas
            IGeoDataset BackLinkDataset = distanceOp.CostBackLink(sourceRaster, costRaster, ref maxDistance, ref valueRaster);

            IGeoDataset outputDataset = distanceOp.CostPath(endRasterLayer.Raster as IGeoDataset, DisDataset, BackLinkDataset, esriGeoAnalysisPathEnum.esriGeoAnalysisPathForEachCell);

            ISaveAs pSaveAs = outputDataset as ISaveAs;
            pSaveAs.SaveAs(fileName, ws, "IMAGINE Image");
            IRasterLayer pCreatRalyr = new RasterLayerClass();
            pCreatRalyr.CreateFromFilePath(outputFileName);

            return pCreatRalyr;
        }
        public static IRasterLayer OpenDEM(string title, ref string name)
        {
            string filePath = MyTools.OpenBrowser(title);
            if (filePath == "") return null;
            name = System.IO.Path.GetFileName(filePath);
            IWorkspaceFactory pWorkspaceFactory = new RasterWorkspaceFactory();
            IWorkspace pWorkspace = pWorkspaceFactory.OpenFromFile(System.IO.Path.GetDirectoryName(filePath), 0);
            IRasterWorkspace pRasterWorkspace = pWorkspace as IRasterWorkspace;
            IRasterDataset pRasterDataset = pRasterWorkspace.OpenRasterDataset(name);
            // 创建金字塔
            IRasterPyramid pRasterPyramid = pRasterDataset as IRasterPyramid;
            if (!pRasterPyramid.Present)
            {
                pRasterPyramid.Create();
            }

            // 栅格图层
            IRasterLayer pRasterLayer = new RasterLayer();
            pRasterLayer.CreateFromDataset(pRasterDataset);

            return pRasterLayer;
        }
    }
}
